package com.jing.weibo.controller.fansattention;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.model.WeiboException;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.FansAttentionType;
import com.jing.weibo.pojo.Fansattention;
import com.jing.weibo.pojo.UserInfo;
import com.jing.weibo.service.fans.FansAttentionService;
import com.jing.weibo.ws.sina.SinaService;

/**
 * 用户关注的Controller
 * @author jing.yue
 * @version 2012/08/29 1.0.0
 */
@Controller
public class AttentionController extends BaseController {

	private static final Logger logger = Logger.getLogger(AttentionController.class);

	@Autowired
	private SinaService sinaService;

	@Autowired
	private FansAttentionService fansAttentionService;

	/**
	 * 获取用户单向关注列表
	 * @return
	 */
	@RequestMapping(value = "/attention/json/onewayAttention")
	@ResponseBody
	public ModelMap onewayAttention(HttpServletRequest request, Fansattention fansattention) {
		// TODO Auto-generated method stub
		//logger.info("获取用户单向关注列表");
		String result = null;
		String weiboMsg = null;
		Map<String, Object> map = null;
		try {
			synchrologInfo(request, FansAttentionType.TYPE_ATTENTION);
			fansattention.setType(FansAttentionType.TYPE_ATTENTION.getCode());
			fansattention.setUsername(getSessionUser(request).getUsername());
			map = fansAttentionService.findOnewayAttention(fansattention);
			result = SUCCESS;
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e));
			result = ERROR_WEIBO;
			weiboMsg = WeiboCons.getErrorMsg(e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取单向关注信息异常!");
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}

	/**
	 * 获取用户关注列表
	 * @return
	 */
	@RequestMapping(value = "/attention/json/myAttention")
	@ResponseBody
	public ModelMap myAttention(HttpServletRequest request, Fansattention fansattention) {
		// TODO Auto-generated method stub
		//logger.info("获取用户关注列表");
		String result = null;
		String weiboMsg = null;
		Map<String, Object> map = null;
		try {
			synchrologInfo(request, FansAttentionType.TYPE_ATTENTION);
			fansattention.setFollowing("true");
			fansattention.setType(FansAttentionType.TYPE_ATTENTION.getCode());
			fansattention.setUsername(getSessionUser(request).getUsername());
			map = fansAttentionService.findAttention(fansattention);
			result = SUCCESS;
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e));
			result = ERROR_WEIBO;
			weiboMsg = WeiboCons.getErrorMsg(e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取关注信息异常!");
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}

	/**
	 * 取消关注的用户
	 * @return
	 */
	@RequestMapping(value = "/attention/json/cancelAttention")
	@ResponseBody
	public ModelMap cancelAttention(HttpServletRequest request, Fansattention fansattention, String uids, String opterType) {
		// TODO Auto-generated method stub
		//logger.info("取消关注的用户");
		String result = null;
		StringBuffer weiboMsg = new StringBuffer();
		StringBuffer errorWeiboMsg = new StringBuffer();
		int count = 0;
		int errorCount = 0;
		String[] uidArr = uids.split(",");
		UserInfo userInfo = getSessionUser(request);
		String username = userInfo.getUsername();
		for (String uid : uidArr) {
			if(uid == null || "".equals(uid.trim())) {
				continue;
			}
			fansattention.setUsername(username);
			fansattention.setFansattentionusername(uid);
			try {
				sinaService.destroyFriendshipsDestroyById(uid, userInfo.getToken());
				opterFansatention(opterType, fansattention);
			} catch (WeiboException e) {
				logger.error(WeiboCons.getErrorMsg(e));
				result = ERROR_WEIBO;
				errorWeiboMsg.append("调用微博接口取消[").append(uid).append("]用户出现异常[").append(WeiboCons.getErrorMsg(e)).append("]!");
				errorCount ++;
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("取消单向关注信息异常!");
				errorCount ++;
			}
			count ++;
		}
		/*try {
			//同步记录
			synchrologInfo(request, FansAttentionType.TYPE_FANS, true);
			synchrologInfo(request, FansAttentionType.TYPE_ATTENTION, true);
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("关注单向粉丝信息异常!");
		}*/
		weiboMsg.append("共取消[").append(count).append(")]位用户: [").append(count - errorCount).append("]位成功! [").append(errorCount).append("]位失败!");
		//logger.info(weiboMsg.toString());
		//logger.info(errorWeiboMsg.toString());
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg.toString());
		modelMap.put("errorWeiboMsg", errorWeiboMsg.toString());
		return modelMap;
	}

	/**
	 * 操作用户
	 * @param opterType
	 * @param fansattention
	 * @throws Exception
	 */
	private void opterFansatention(String opterType, Fansattention fansattention) throws Exception {
		// TODO Auto-generated method stub

		//单向关注
		if("onewayAttention".equals(opterType)) {
			//根据类型/用户名/关注的用户删除记录
			fansAttentionService.deleteAttentionByTypeUsernameFausername(fansattention);
		}
		//我的关注
		else if("myAttention".equals(opterType)) {
			//根据类型/用户名/关注的用户删除记录
			fansAttentionService.deleteAttentionByTypeUsernameFausername(fansattention);
		}
		//互粉粉丝
		else if("mutualPowderFans".equals(opterType)) {
			//取消关注后将变成单向粉丝
			fansattention.setFollowing("false");
			fansAttentionService.updateFansattentionFollow(fansattention);
			//删除关注中记录
			Fansattention fa = new Fansattention();
			fa.setUsername(fansattention.getUsername());
			fa.setFansattentionusername(fansattention.getFansattentionusername());
			fa.setType(FansAttentionType.TYPE_ATTENTION.getCode());
			fansAttentionService.deleteAttentionByTypeUsernameFausername(fa);
		}
		//我的粉丝
		else if("myFans".equals(opterType)) {
			//取消关注后将变成单向粉丝
			fansattention.setFollowing("false");
			fansAttentionService.updateFansattentionFollow(fansattention);
			//删除关注中记录
			Fansattention fa = new Fansattention();
			fa.setUsername(fansattention.getUsername());
			fa.setFansattentionusername(fansattention.getFansattentionusername());
			fa.setType(FansAttentionType.TYPE_ATTENTION.getCode());
			fansAttentionService.deleteAttentionByTypeUsernameFausername(fa);
		}
	}
}